package cn.sinata.wanglin.neighbor.activity;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xilada.xldutils.activitys.RecyclerListActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.VillageNeighborAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.VillageNeighbor;
import cn.sinata.wanglin.neighbor.view.RxTextView;
import cn.sinata.wanglin.neighbor.view.SearchEditText;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.net.model.util.ResultSubscriber;
import cn.sinata.wanglin.property.activity.SearchVillageActivity;
import cn.sinata.wanglin.village.activity.AllUserInfoActivity;
import cn.sinata.wanglin.village.activity.ChoiceVillageActivity;
import rx.android.schedulers.AndroidSchedulers;

public class VillageNeighborActivity extends RecyclerListActivity {

    private VillageNeighborAdapter villageNeighborAdapter;
    private ArrayList<VillageNeighbor> mVillageNeighbors = new ArrayList<>();
    private int type = 0;//不同入口，展示不同,通讯录进入需要展示右边按钮
    private String keyWord="";
    private String id;
    private String userId;
    private SearchEditText searchEditText;
    private boolean resetData = false;

    @Override
    protected void initView() {
        super.initView();
        String name = getIntent().getStringExtra("name");
        setTitle(name);
        type = getIntent().getIntExtra("type",0);
        id = getIntent().getStringExtra("id");
        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        if (type == 1) {
            addRightButton("其他小区", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ActivityUtil.create(mContext)
                            .go(SearchVillageActivity.class)
                            .startForResult(3);
                }
            });

            getTitleView().setEnabled(true);

            getTitleView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtil.create(mContext)
                            .go(ChoiceVillageActivity.class)
                            .startForResult(0);
                }
            });
        }

        if (type == 1) {
            if (MyApplication.houseid == null || TextUtils.equals("-1", MyApplication.houseid)) {
                ActivityUtil.create(this)
                        .go(ChoiceVillageActivity.class)
                        .startForResult(0);
            } else {
                id = MyApplication.houseid;
                setTitleArrowText(MyApplication.houseName);
                showDialog();
                getData();
            }
        } else {
            showDialog();
            getData();
        }
    }

    @Override
    protected RecyclerView.Adapter setAdapter() {
        villageNeighborAdapter = new VillageNeighborAdapter(mVillageNeighbors);
        View headerView = LayoutInflater.from(this).inflate(R.layout.header_village_neighbor_layout,null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);

        searchEditText = (SearchEditText) headerView.findViewById(R.id.tv_search);
        villageNeighborAdapter.setHeaderView(headerView);
        villageNeighborAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ActivityUtil.create(mContext)
                        .go(AllUserInfoActivity.class)
                        .put("friendID",mVillageNeighbors.get(position).getId())
                        .startForResult(16);
            }
        });
        searchEditText.setOnSearchActionListener(new SearchEditText.OnSearchActionListener() {
            @Override
            public void onSearch() {

            }
        });

        setSearchTextChange();

        return villageNeighborAdapter;
    }

    void getData(){
        resetData =true;
        searchEditText.getText().clear();
        HttpManager.getHousingUserList(id,userId)
                .subscribe(new ResultDataSubscriber<ArrayList<VillageNeighbor>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<VillageNeighbor> villageNeighbors) {

                        if (villageNeighbors.size() == 0 ) {
                            setLoadMoreText("该小区暂无业主");
                        }
                        mVillageNeighbors.clear();
                        if (villageNeighbors.size() > 0) {
                            mVillageNeighbors.addAll(villageNeighbors);
                        }
                        int size = mVillageNeighbors.size();
                        for (int i = 0; i < size; i++) {
                            mVillageNeighbors.get(i).setIndex(i+1);
                        }
                        villageNeighborAdapter.notifyDataSetChanged();
                        villageNeighborAdapter.resetFilter();
                        resetData = false;
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0 || requestCode == 3) {
                setTitleArrowText(MyApplication.houseName);
                id = MyApplication.houseid;
                keyWord = "";
                showDialog();
                getData();
            }
        }
    }

    private void setSearchTextChange(){

        RxTextView.textChanges(searchEditText)
                .debounce(150, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultSubscriber<CharSequence>(this){
                    @Override
                    public void onNext(CharSequence charSequence) {
                        super.onNext(charSequence);
                        setRefreshing(false);
                        keyWord = charSequence.toString();
                        if (mVillageNeighbors.size() > 0 && !resetData) {
                            villageNeighborAdapter.getFilter().filter(charSequence);
                        }
                    }
                });
    }

    @Override
    protected SwipeRefreshRecyclerLayout.Mode getMode() {
        return SwipeRefreshRecyclerLayout.Mode.Top;
    }

    @Override
    protected void pullDownRefresh() {
        super.pullDownRefresh();
        if (mVillageNeighbors != null && mVillageNeighbors.size() > 0) {
            searchEditText.setText(keyWord);
        } else {
            getData();
        }
    }

    private void setTitleArrowText(CharSequence text){
        Spannable spannable = new SpannableString(text+"v");
        spannable.setSpan(new ImageSpan(this,R.mipmap.ic_arrow_down_white),text.length(),text.length()+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        setTitle(spannable);
    }
}
